package edu.bit.water.controller;


import edu.bit.water.dao.MetaWaterDao;
import edu.bit.water.dao.WarningRuleDao;
import edu.bit.water.dto.DateUtils;
import edu.bit.water.dto.WarningRule;
import edu.bit.water.dto.WaterWarningCondition;
import edu.bit.water.entity.Companys;
import edu.bit.water.entity.WarningRecord;
import edu.bit.water.service.*;
import edu.bit.water.util.DateTimeUtil;
import edu.bit.water.util.ListToSqlString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/warning_record")
public class WarningRecordController {
    @Autowired
    private WarningRecordService warningRecordService;
    @Autowired
    private CompanysService companysService;
    @Autowired
    private WarningRuleDao warningRuleDao;
    @Autowired
    private MetaWaterDao metaWaterDao;

    @Autowired
    private EntitySensorService entitySensorService;

    @Autowired
    private EntityWaterService entityWaterService;

//    @ResponseBody
//    @RequestMapping("query_all_record")
//    public Map<String, Object> queryAllRecord() {
//        List<String> sensors = warningRecordService.selectAllSensors();
//        String startTime = "2010-01-01 00:00:00";
//        String endTime = DateUtils.getNowDate();
//        return queryWarningRecord(sensors, startTime, endTime, 0);
//    }

    @ResponseBody
    @RequestMapping("query_all_record_by_companyid")
    public Map<String, Object> queryAllRecordByCompanyId(WarningRule warningRule) throws ParseException {
//        List<String> sensors = warningRecordService.selectAllSensors();
        List<Map<String, Object>> sList = entitySensorService.selectEntitySensor("" + warningRule.getCompanyId());
        List<String> sensors = new ArrayList<>();
        for (Map<String, Object> map : sList) {
            sensors.add(map.get("SENSOR_ROW_ID").toString());
        }
        String startTime = "2022-03-15 18:00:00";
        String endTime = DateUtils.getNowDate();
        return queryWarningRecord(sensors, startTime, endTime, warningRule.getCompanyId());
    }

    @ResponseBody
    @RequestMapping("/query_names")
    public Map<String, Object> queryNames(@RequestParam(name = "sensorRowIds") List<String> sensorRowIds,
                                          @RequestParam(name = "companyId") int companyId) {
        List<String> names = new ArrayList<>();
        Map<String, Object> result = new HashMap<>();
        for (int i = 0; i < sensorRowIds.size(); i++) {
            List<String> name = warningRecordService.querySensorNames(sensorRowIds.get(i), companyId);
            System.out.println("hahaha");
            System.out.println("sensorRowIds.get(i):" + sensorRowIds.get(i));
            System.out.println("companyId:" + companyId);
            if (name.size() != 0) {
                names.add(name.get(0));
            } else {
                names.add("命名冲突");
            }

        }
        result.put("names", names);
        return result;
    }

    @ResponseBody
    @RequestMapping("/query_record")
    public Map<String, Object> queryWarningRecord(@RequestParam(name = "sensorRowIds") List<String> sensorRowIds,
                                                  @RequestParam(name = "startTime") String startTime,
                                                  @RequestParam(name = "endTime") String endTime,
                                                  @RequestParam(name = "companyId") int companyId
    ) throws ParseException {
        //用来返回的map
        Map<String, Object> modelMap = new HashMap<>();
        WaterWarningCondition waterWarningCondition = new WaterWarningCondition(startTime, endTime);
        waterWarningCondition.setCompanyId(companyId);
        //用来存储没有规则的传感器编号
        List<String> noRuleId = new ArrayList<>();
        for (int i = 0; i < sensorRowIds.size(); i++) {
            //查询当前监控设备和监控属性
            List<WarningRule> warningRules = warningRecordService.queryWarningRuleBySensorIdAndCompanyId(sensorRowIds.get(i), companyId);

            //未找到阈值，跳过
            if (warningRules == null || warningRules.size() <= 0) {
                noRuleId.add(sensorRowIds.get(i));
                continue;
            }
        }
        List<WarningRecord> list = warningRecordService.queryWarningRecordByWarningConditionAndCompanyId(waterWarningCondition);
        modelMap.put("NoRuleId", noRuleId);
        List<Map<String, Object>> modelList = new ArrayList<>();
        for(int i = 0; i < list.size(); i++) {
            Map<String, Object> tmpMap = new HashMap<>();
            tmpMap.put("标识符", list.get(i).getEntityWaterId());
            tmpMap.put("传感器编号", list.get(i).getSensorRowId());
            tmpMap.put("CREATED_AT", DateTimeUtil.dateToStr(list.get(i).getCreatedAt()));
            tmpMap.put("规则名称", list.get(i).getRule());
            tmpMap.put("传感器名称", list.get(i).getSensorRowId());
            tmpMap.put("实际值", list.get(i).getValue());
            tmpMap.put("预警", list.get(i).getWarning());
            modelList.add(tmpMap);
        }

        modelMap.put("rows", modelList);

        List<String> names = new ArrayList<>();
        for (int i = 0; i < sensorRowIds.size(); i++) {
            List<String> name = warningRecordService.querySensorNames(sensorRowIds.get(i), companyId);
//            System.out.println("hahaha");
//            System.out.println("sensorRowIds.get(i):" + sensorRowIds.get(i));
//            System.out.println("companyId:" + companyId);
            if (name.size() != 0) {
                names.add(name.get(0));
            } else {
                names.add("命名冲突");
            }

        }
        modelMap.put("names", names);
        return modelMap;
    }

    @ResponseBody
    @RequestMapping("/queryworkshop")
    List<String> queryWorkshop() {
        return warningRecordService.queryWorkshop();
    }

    @ResponseBody
    @RequestMapping("/queryworkshopByCompanyName")
    List<String> queryWorkshopByCompanyName(Companys companys) {
        String company_name = companys.getCompanyName();
        int company_id = companysService.selectIdByName(company_name);
        return warningRecordService.queryWorkshopByCompanyId(company_id);
    }

    /**
     * 通过公司id查询该公司的所有所在位置（车间）
     *
     * @param companys
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryworkshopByCompanyId")
    List<String> queryWorkshopByCompanyId(Companys companys) {
        int company_id = companys.getId();
        return warningRecordService.queryWorkshopByCompanyId(company_id);
    }


    @ResponseBody
    @RequestMapping(value = "/querysortbyworkshop")
    List<String> querySortByWorkshop(@RequestParam("techProcessId") String techProcessId,
                                     @RequestParam(required = false) List<String> workshop) {
        if (workshop == null) {
            return new ArrayList<>();
        }
        return warningRecordService.querySortByWorkshop(ListToSqlString.toString(workshop), techProcessId);
    }

    @ResponseBody
    @RequestMapping(value = "/querysensorrowidbyworkshopandsort")
    List<String> querySortByWorkshop(@RequestParam("techProcessId") String techProcessId,
                                     @RequestParam(required = false) List<String> workshop,
                                     @RequestParam(required = false) List<String> sort) {
        if (workshop == null || sort == null) {
            return new ArrayList<>();
        }
        return warningRecordService.querySensorRowIdByWorshopAndsort(techProcessId, ListToSqlString.toString(workshop), ListToSqlString.toString(sort));
    }

    @ResponseBody
    @RequestMapping(value = "/querySensorRowIdByWorkShopAndSort")
    List<String> querySortByWorkshopAndSort(@RequestParam("businessId") String businessId, @RequestParam(required = false) List<String> workshop, @RequestParam(required = false) List<String> sort) {
        if (workshop == null || sort == null) {
            return new ArrayList<>();
        }
        return warningRecordService.querySensorRowIdByWorkshopAndsort(businessId, ListToSqlString.toString(workshop), ListToSqlString.toString(sort));
    }

    /**
     * 产生预警记录信息
     */
    public void warningRecordGenerate() {
        Date lastTime = warningRecordService.queryLastTime();
        List<String> sensorRowIds = entityWaterService.querySensorRowIdsByTime(lastTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        WaterWarningCondition waterWarningCondition = new WaterWarningCondition(sdf.format(lastTime), DateUtils.getNowDate());
        for (int i = 0; i < sensorRowIds.size(); i++) {
            List<WarningRule> warningRules = warningRecordService.queryWarningRuleBySensorId(sensorRowIds.get(i));
            if (warningRules == null || warningRules.size() <= 0) {
                continue;
            }
            List<HashMap<String, Object>> teMap = warningRecordService.queryRecordByCondition(sensorRowIds.get(i), waterWarningCondition);
            for (HashMap<String, Object> entry : teMap) {
                WarningRecord warningRecord = new WarningRecord();
                Map<String, Object> tmpMap = new HashMap<>();
                tmpMap.put("ID", entry.get("ID"));
                tmpMap.put("SENSOR_ROW_ID", sensorRowIds.get(i));
                tmpMap.put("CREATED_AT", DateTimeUtil.dateToStr((Date) entry.get("CREATED_AT")));
                tmpMap.put("RULE", warningRules.get(0).getName());
                tmpMap.put("VALUE", entry.get("REALVALUE"));
                //tmpMap.put("监控属性", csName);
                String tmprealValue = entry.get("REALVALUE").toString();
                double realValue = Double.parseDouble(tmprealValue);
                boolean flag = false;
                //处于三级预警低限到二级预警低限值之间触发三级预警
                if (realValue >= warningRules.get(0).getRuleValue3L() && realValue < warningRules.get(0).getRuleValue2L()) {
                    warningRecord.setWarning("三级低限预警");
                    flag = true;
                } else if (realValue >= warningRules.get(0).getRuleValue2L() && realValue < warningRules.get(0).getRuleValue1L()) {
                    warningRecord.setWarning("二级低限预警");
                    flag = true;
                } else if (realValue >= warningRules.get(0).getRuleValue1L() && realValue < warningRules.get(0).getRuleValue0L()) {
                    warningRecord.setWarning("一级低限预警");
                    flag = true;
                } else if (realValue >= warningRules.get(0).getRuleValue0L() && realValue < warningRules.get(0).getRuleValue0H()) {
                    warningRecord.setWarning("正常运行范围");
                } else if (realValue >= warningRules.get(0).getRuleValue0H() && realValue < warningRules.get(0).getRuleValue1H()) {
                    warningRecord.setWarning("一级高限预警");
                    flag = true;
                } else if (realValue >= warningRules.get(0).getRuleValue1H() && realValue < warningRules.get(0).getRuleValue2H()) {
                    warningRecord.setWarning("二级高限预警");
                    flag = true;
                } else if (realValue >= warningRules.get(0).getRuleValue2H() && realValue < warningRules.get(0).getRuleValue3H()) {
                    warningRecord.setWarning("三级高限预警");
                    flag = true;
                } else {
                    warningRecord.setWarning("实际值超出预警规则范围");
                    flag = true;
                }
                if (flag) {
                    warningRecord.setEntityWaterId(entry.get("ID").toString());
                    warningRecord.setSensorRowId(sensorRowIds.get(i));
                    warningRecord.setValue(entry.get("REALVALUE").toString());
                    warningRecord.setRule(warningRules.get(0).getName());
                    warningRecord.setRuleId(warningRules.get(0).getId());
                    warningRecord.setCompanyId(warningRules.get(0).getCompanyId());
                    warningRecord.setCreatedAt((Date) entry.get("CREATED_AT"));
                    warningRecordService.addWarningRecord(warningRecord);
                }

            }
        }
    }

    /**
     * 查询各个时间段内的报警比例
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query_index_data")
    Map<String, Object> queryIndexData() throws ParseException {
        entityWaterService.timeDataTransform();

        warningRecordGenerate();

        return warningRecordService.queryIndexData();
    }
}